/**
 * <p>带编辑gridpanel控件(直接在查询列表上编辑)</p>
 * xtype = cceafeditorgridpanel

 * @module Ext-ux-cceaf-control
 * @class cceaf.control.EditorGridPanel
 * @extends Ext.grid.GridPanel
 * @since 1.0
 */
Ext.define('cceaf.control.EditorGridPanel',{
	extend: 'Ext.grid.GridPanel', 
    alias: 'widget.cceafeditorgridpanel',
    requires: [
        'cceaf.control.ToolbarPaging'
    ],
    
    constructor: function(config){
		config = config || {};
		
		cceaf.control.EditorGridPanel.superclass.constructor.apply(this, arguments);
	},
	
	/**
	 * 模块名称，在grid的title上显示
	 *
     * @property moduleName 
     * @type String
     * @default null
     */
	moduleName: "",
	
	/**
	 * 是否显示分页栏，默认显示
	 *
     * @property hasPagingToolbar 
     * @type boolean
     * @default true
     */
	hasPagingToolbar: true,
	
	/**
	 * 查询的action
	 *
     * @property queryAction 
     * @type String
     * @default null
     */
	queryAction: null,
	
	/**
	 * 增加的action<p>
	 * 点击该按钮增加1行，，不需要通过action获取记录，此处可随便填写，只要不为null
	 *
     * @property addAction
     * @type String
     * @default null
     */
	addAction: null,
	
	/**
	 * 编辑的action，一般为action中的findByKey<p>
	 * 编辑的gridpanel是对当前选择列的编辑，不需要通过action获取记录，此处可随便填写，只要不为null
	 *
     * @property editAction 
     * @type String
     * @default null
     */
	editAction: null,
	
	/**
	 * 当前操作行提交的action，如果是新增的为save，如果是更新的为update
	 *
     * @property saveAndUpdateAction 
     * @type String
     * @default null
     */
	saveAndUpdateAction: null,
	
	/**
	 * 删除的action
	 *
     * @property deleteAction 
     * @type String
     * @default null
     */
	deleteAction: null,
	
	/**
	 * 打印查询列表的action
	 *
     * @property printListAction 
     * @type String
     * @default null
     */
	printAction: null,
	
	/**
	 * 把查询列表导出成excel的action
	 *
     * @property exportExcelAction 
     * @type String
     * @default null
     */
	exportExcelAction: null,
	
	/**
	 * 主键名称集合，以,分开
	 *
     * @property masterKeyIds 
     * @type String
     * @default null
     */
	masterKeyIds: null,
	
	/**
	 * 查询区
	 *
     * @property queryToolbar 
     * @type Array(toolbar)
     * @default null
     */
	queryToolbar: null,
	
	/**
	 * 操作区的toolbar，在组装后的toolbar后追加
	 *
     * @property operateToolbar 
     * @type toolbar
     * @default null
     */
	operateToolbar: null,
	
	/**
	 * 操作区的toolbar
	 *
     * @property reOperateToolbar 
     * @type attribute toolbar
     * @default null
     */
	reOperateToolbar: null,
	
	/**
	 * 是否显示默认查询控件,默认显示
	 *
     * @property showqueryToolbar 
     * @type attribute Boolean
     * @default false
     */
	isShowQueryToolbar:true,
	
	initComponent : function(){
    	var config = this;
		
    	var columns = config.columns;
		if (!columns) {
			cceaf.util.ExtHelper.showErrorDialog("必须设置grid的columns！");
		}
    	
		var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {  
			pluginId: 'pluginIdOfcceafeditorgridpanel',
            clicksToEdit : 2,//默认双击修改行数据  
            //clicksToMoveEditor : 1,  
            autoCancel : false  
        });  
		
		//定义数据源
	    var ds = new Ext.data.Store({
	    	proxy: {
	    		type: 'ajax',
	    		url: config.queryAction,
	    		reader: {
					type: 'json',
					root: 'data',
					totalProperty: 'totalCount',
					messageProperty: 'message'
				}
			},
	        listeners: {
	        	'load': function(){
	        		var jr = ds.getProxy().getReader();
	        		if(!jr.jsonData) {
	        			cceaf.util.ExtHelper.showErrorDialog("没有设置正确的action或没有返回正确的json字符串！");
	        			return;
	        		}
	        		
	        		var message = jr.jsonData.message;
	        		var url = jr.jsonData.url;
	        		cceaf.util.ExtHelper.showInfoDialog(message,url);
	        	},
	        	'loadexception': function(){
	        		var jr = ds.getProxy().getReader();
	        		if(jr.jsonData){
		        		var message = jr.jsonData.message;
		        		var url = jr.jsonData.url;
		        		cceaf.util.ExtHelper.showErrorDialog(message,url);
	        		}
	        		else{
	        			cceaf.util.ExtHelper.showErrorDialog("返回无效的JSONDATA数据");
	        		}
	        	}
	        	
	        },
	        
	        autoDestroy: true,  
	    	pageSize: szpshang.Global.PAGE_SIZE,
	    	model: config.model
	    		
	    });
        
	    /**
	     * 默认查询区
	     */
	    var tempQueryToolbar = config.queryToolbar;
	    var queryToolbar = [], j=0;
	    //此部分解决extjs的一个bug，移除queryToolbar中dock非top的toolbar
	    Ext.Array.each(tempQueryToolbar, function(dockItem) {
	    	if (dockItem.dock == 'top') {
	    		queryToolbar[j++] = dockItem;
	    	}
	    });
	    if(this.isShowQueryToolbar){
			if(queryToolbar.length == 0){
				queryToolbar = [];
				queryToolbar[0] = {
					dock: 'top', 
					xtype: 'toolbar',
					items: [
						{xtype: "tbfill"},
			        	{itemId: 'btnQuery', iconCls: 'page_queryIcon', text: ' 查询 ', pressed: true},
			        	'-',
			        	{itemId: 'btnReset', iconCls: 'page_resetIcon', text: ' 重置 ', pressed: true}
					]
				};
			}
	    }
	    
	    /**
		 * 默认操作区
		 */
		var operateArea = [],i=0;
		if(config.addAction){
			operateArea[i] = {itemId: 'btnAdd', text: ' 新增 ', iconCls: 'page_addIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.editAction){
			operateArea[i] = {itemId: 'btnEdit', text: ' 编辑 ', iconCls: 'page_editIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.viewAction){
			operateArea[i] = {itemId: 'btnView', text: ' 查看 ', iconCls: 'page_viewIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.writeOffAction){
			operateArea[i] = {itemId: 'btnWriteOff', text: ' 注销 ', iconCls: 'page_writeOffIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.deleteAction){
			operateArea[i] = {itemId: 'btnDelete', text: ' 删除 ', iconCls: 'page_deleteIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.statAction){
			operateArea[i] = {itemId: 'btnStat', text: ' 统计 ', iconCls: 'statIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.printBillAction){
			operateArea[i] = {itemId: 'btnPrintBill', text: ' 打印表单 ', iconCls: 'printBillIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.printListAction){
			operateArea[i] = {itemId: 'btnPrintList', text: ' 打印列表 ', iconCls: 'printListIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		if(config.exportExcelAction){
			operateArea[i] = {itemId: 'btnExportExcel', text: ' 导出XLS ', iconCls: 'exportExcelIcon', pressed: true};
			i++;
			operateArea[i] = '-';
			i++;
		}
		
		var operateToolbar = config.operateToolbar;
		if(operateToolbar == null){
			var reOperateToolbar = config.reOperateToolbar;
			if (reOperateToolbar == null) {
				operateToolbar = {
					//dock: 'top', 
					xtype: 'toolbar',
					items: operateArea
				};
			} else {
				operateToolbar = {
					//dock: 'top', 
					xtype: 'toolbar',
					items: reOperateToolbar
				};
			}
		}else {
			//var array = Ext.Array.merge(operateArea,operateToolbar);
			var array = operateArea.concat(operateToolbar);
			operateToolbar = {
				//dock: 'top', 
				xtype: 'toolbar',
				items: array
			};
		}

		var pagingtoolbar = {
			xtype: 'cceaftoolbarpaging',
			store: ds,
	        dock: 'bottom',  
	        displayInfo: true,
	        displayMsg:'当前显示 {0} - {1}条记录 /共 {2}条记录',
	      	emptyMsg:'无显示数据'
		};
		
		var dockedItems = queryToolbar;
		dockedItems[dockedItems.length] = operateToolbar;
		if (config.hasPagingToolbar === true) {
			dockedItems[dockedItems.length] = pagingtoolbar;
		}
		
		var height = config.height;
		var width = config.width;
		if(config.height == null){
			//height = cceaf.util.ExtHelper.getBodyHeight();
			
			height = cceaf.util.ExtHelper.getMainContentHeight();
		}
		if(config.width == null){
			//width = cceaf.util.ExtHelper.getBodyWidth();
			
			width = cceaf.util.ExtHelper.getMainContentWidth();
		}
		
		//alert(width);
		//alert(height);
		
		var title = '';
		if (config.moduleName) {
			title = config.moduleName + '信息';
		}
		
		Ext.applyIf(this, {
			store: ds,
			title: config.moduleName + '信息',
	        border: true,
	        frame: true,
	        disableSelection: false, // 允许选择行 *  
	        selType: 'rowmodel', // 选择类型设置为：行选择  
	        plugins: [rowEditing],
	        loadMask: {msg:'正在加载数据，请稍侯……'},
	        dockedItems:dockedItems,
	        listeners : {  
	            'selectionchange' : function(sm, selections) {
	                //this.down('#btnDelete').setDisabled(selections.length == 0);  
	            },
	            'edit': function(editor, e){
	            	this.onEdit(e);
	            }
	        }
		});

		if(!config.autoWidth){
			Ext.applyIf(this, {
		        width: width
			});
		}
		if(!config.autoHeight){
			Ext.applyIf(this, {
				height: height
			});
		}
		
		cceaf.control.EditorGridPanel.superclass.initComponent.call(this);
	},
	
	/**
	 * 设置每行的class
	 */
	viewConfig: {
		forceFit:true,
		enableRowBody:true,
		getRowClass : function(record, rowIndex, p, ds){
			return '';
		}
	},

    initEvents: function() {
    	cceaf.control.EditorGridPanel.superclass.initEvents.call(this);
    	
    	//注册查询按钮事件
    	if(this.down('#btnQuery')){
    		this.down('#btnQuery').on('click',this.page_query);
    	}
    	
    	//注册重置按钮事件
    	if(this.down('#btnReset')){
    		this.down('#btnReset').on('click',this.page_reset);
    	}
    	
    	//注册操作区按钮事件
    	if(this.down('#btnAdd')){
    		this.down('#btnAdd').on('click',this.page_add);
    	}
    	if(this.down('#btnEdit')){
    		this.down('#btnEdit').on('click',this.page_edit);
    	}
    	if(this.down('#btnDelete')){
    		this.down('#btnDelete').on('click',this.page_delete);
    	}
    	if(this.down('#btnPrint')){
    		this.down('#btnPrint').on('click',this.print);
    	}
    	if(this.down('#btnExportExcel')){
    		this.down('#btnExportExcel').on('click',this.exportExcel);
    	}
    	
    	//注册其他事件
    	this.registerEvent();
    },
	
    /**
     * 查询对象
     */
    page_query: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	//var queryGrid = this.up('gridpanel');
    	
    	var queryGrid = this.findParentByType('cceafeditorgridpanel');
    	
    	if (!queryGrid.model) {
			cceaf.util.ExtHelper.showInfoDialog('请设置gridpanel的model！');
			return;
		}
    	
    	//加载数据
    	var queryParams = {};
    	var queryAreaItems = queryGrid.query('textfield');
    	for(var i=0;queryAreaItems != null && i<queryAreaItems.length;i++){
    		var item = queryAreaItems[i];
    		var itemValue = item.getValue();
    		//alert(item.getName());
    		var spiltIndex = item.getName().lastIndexOf('-');
    		if (spiltIndex != -1) {
    			cceaf.util.ExtHelper.showInfoDialog('查询条件必须设置name属性！');
    			return;
    		}
    		
    		itemPrefixIndex = item.getName().lastIndexOf('q_');
			if(itemPrefixIndex == 0){
				if(itemValue == null){
					eval("queryParams." + item.getName() + " = ''");
				}
				else{
					if(Ext.isDate(itemValue)){
						itemValue = Ext.Date.format(itemValue,'Y-m-d');
					}
					eval("queryParams." + item.getName() + " = '" + itemValue + "'");
				}
			}
    	}
		
    	queryGrid.getStore().proxy.extraParams = queryParams;
    	queryGrid.getStore().load({params:{isquery:true}});
    },
    
    /**
     * 重置查询条件，默认实现为清空，自定义实现需要重载该方法
     */
    page_reset: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	
    	var queryAreaItems = queryGrid.query('textfield');
    	queryAreaItems.forEach(function(item){
    		itemPrefixIndex = item.getId().lastIndexOf('q_');
			if(itemPrefixIndex == 0){
				item.setValue("");
			}
		});
    },
    
    /**
     * 新增对象
     */
    page_add: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	
    	var rowEditing = queryGrid.getPlugin('pluginIdOfcceafeditorgridpanel');
		var recordData = Ext.ModelManager.create({}, 'QueryModel');  
		queryGrid.getStore().insert(0, recordData);
		rowEditing.startEdit(queryGrid.getStore().getAt(0), 2);  
    	//设置初始值
		queryGrid.initAddPage();
    },
    
    /**
     * 编辑对象
     */
    page_edit: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	
    	var rowEditing = queryGrid.getPlugin('pluginIdOfcceafeditorgridpanel');
    	var sm = queryGrid.getSelectionModel(); 
    	//alert(sm.getLastSelected());
    	//var model = Ext.ModelManager.getModel('QueryModel');
    	//alert(model);
    	rowEditing.startEdit(sm.getLastSelected(),2);
    },
    
    /**
     * 删除对象
     */
    page_delete: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	
    	//var rowEditing = queryGrid.getPlugin('pluginIdOfcceafeditorgridpanel');
    	//var sm = queryGrid.getSelectionModel();  
        //var records = sm.getSelection();  
        //rowEditing.cancelEdit();  
        //store.remove(records);  
        //sm.select(0);  
        //for (var i = 0; i < records.length; i++) {  
            //records[i].data['code'];  
        //}
        
    	//获取要删除对象的主键集
    	var selModel = queryGrid.getSelectionModel();
    	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择要删除的行');
    		return;
    	}
    	else{
    		//确定要删除对象
    		Ext.MessageBox.show({
				title:'确认提示框',
				modal: true,
				msg: '此操作不能回退，确信要删除您选中的对象吗？',
				minWidth: 200,
				buttons: Ext.MessageBox.YESNO,
				icon: Ext.MessageBox.QUESTION,
				fn:function(btn){
					if(btn == 'yes'){
						
						//得到删除对象的主键集
						var masterkeys = queryGrid.masterKeyIds.split(',');
						var params = {};
						for(var i=0;i<masterkeys.length;i++){
							var ids = "";
				    		selModel.getSelection().forEach(function(selection){
				    			ids = ids + selection.get(masterkeys[i]) + ",";
				    		});
				    		eval("params." + masterkeys[i] + "s = '" + ids + "';");
						}
						
			    		Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
			    		Ext.Ajax.request({
			   				url: queryGrid.deleteAction,
			   				//params: { ids: ids },
			   				params: params,
			   				success: function(response){
			   					var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
			   					if(isProcessSucess){
			   						queryGrid.getStore().load({params:{isquery:true}});
			   					}
			   				},
			   				failure: function(response){
			   					cceaf.util.ExtHelper.processAjaxRequest(response,false);
			   				}
						});
					}
				}
			});
    	}
    },
    
    /**
     * 打印表单
     */
    print: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	var url = queryGrid.printAction;
    	cceaf.util.CceafHelper.openUrl(url);
    },
    
    /**
     * 导出到Excel
     */
    exportExcel: function(){
    	//var queryGrid = Ext.getCmp('queryGrid');
    	var queryGrid = this.up('gridpanel');
    	var url = queryGrid.exportExcelAction;
    	cceaf.util.CceafHelper.openUrl(url);
    },
    
    /**
     * 新增表单，设置初始值
     */
    initAddPage: function(){
    	
    },
    
    /**
     * 表单载入数据后,设置特殊值表单值
     */
    initEditPage: function(){
    	
    },
    
    /**
     * 注册其他事件
     */
    registerEvent: function(){
    	
    },
    
    /**
     * 编辑事件处理
     */
    onEdit: function(e){
    	var queryGrid = this;
    	e.record.commit(); 
    	
    	var params = {};
    	var gridColumnNumber = queryGrid.columns.length;
    	for(var j=1;j<gridColumnNumber;j++){
			var column = queryGrid.columns[j];
			var fieldName = column.dataIndex;
			if(fieldName){
				if (e.record.data[fieldName]) {
					eval("params." + fieldName + " = '" + e.record.data[fieldName] + "'");
				}
			}
    	}
    	//alert(Ext.JSON.encode(params));
    	//提交数据到服务器
      	Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
      	Ext.Ajax.request({
      		url: this.saveAndUpdateAction,
      		params: params,
      		success: function(response){
      			cceaf.util.ExtHelper.processAjaxRequest(response,true);
      			//var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
      			queryGrid.getStore().load({params:{isquery:true}});
   			},
   			failure: function(response){
   				cceaf.util.ExtHelper.processAjaxRequest(response,false);
   			}
      	});
    }
    
});